package com.yhy.gateway.exception;

import com.yhy.common.core.result.Result;
import com.yhy.common.core.result.ResultEnum;
import com.yhy.gateway.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 无效token/token过期 自定义响应
 */
@Slf4j
@Component
public class ServerAuthenticationEntryPoint implements org.springframework.security.web.server.ServerAuthenticationEntryPoint {

    /**
     * {@link JwtTimestampValidator#validate(org.springframework.security.oauth2.jwt.Jwt)}
     *
     * @param exchange exchange
     * @param e        e
     * @return Mono
     */
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        log.warn("访问异常: {}, {}", exchange.getRequest().getPath(), e.getLocalizedMessage(), e);
        ResultEnum resultEnum;
        resultEnum = ResultEnum.ACCESS_UNAUTHORIZED;
        if (e instanceof AuthenticationCredentialsNotFoundException) {
            log.debug("token 为空或权限不足");
        }
        if (e instanceof InvalidBearerTokenException) {
            log.debug("token 过期或失效");
            resultEnum = ResultEnum.TOKEN_INVALID_OR_EXPIRED;
        }
        return ResponseUtils.writeErrorInfo(exchange, HttpStatus.UNAUTHORIZED, e, Result.fail(resultEnum));
    }

}
